import OpenAI from "openai";
import express from "express";
import cors from "cors";
const app = express();
app.use(express.json());
app.use(
  cors({
    origin: "http://localhost:5173", // 替换成你的前端域名
    methods: ["GET", "POST"],
    credentials: true,
  })
);

const client = new OpenAI({
  baseURL: "https://ai.gitee.com/v1",
  apiKey: "SBWLPNY4HHJVSNQIKGD8QJAG1SPOWNF8QPRDEP11",
  defaultHeaders: { "X-Failover-Enabled": "true" },
});

// 项目启动时立即执行一次测试连接
(async () => {
  try {
    const response = await client.chat.completions.create({
      model: "DeepSeek-R1-Distill-Qwen-14B",
      messages: [{ role: "user", content: "测试连接" }],
    });
    console.log("AI服务连接成功");
  } catch (error) {
    console.error("AI服务连接失败:", error);
  }
})();

const createChatCompletion = async (message) => {
  const response = await client.chat.completions.create({
    model: "DeepSeek-R1-Distill-Qwen-14B",
    stream: true,
    max_tokens: 1024,
    temperature: 0.6,
    top_p: 0.7,
    top_k: 50,
    frequency_penalty: 0,
    messages: [
      {
        role: "system",
        content:
          "You are a helpful and harmless assistant. You should think step-by-step.",
      },
      {
        role: "user",
        content: message,
      },
    ],
  });
  return response;
};

// app.post("/sendMessage", (req, res) => {
//   const { message } = req.body;
//   res.json({
//     message: "服务器收到消息",
//     receivedMessage: message,
//   });
// });

app.get("/sendMessage", async (req, res) => {
  const { message } = req.query;

  // 设置响应头以支持 SSE
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");

  try {
    const response = await createChatCompletion(message);

    // 处理流式响应
    for await (const chunk of response) {
      if (chunk.choices[0].delta.content) {
        const content = chunk.choices[0].delta.content;
        res.write(
          `data: ${JSON.stringify({
            content,
          })}\n\n`
        );
      }
    }

    // 发送结束信号
    res.write("data: [DONE]\n\n");
    res.end();
  } catch (error) {
    console.error("Error:", error);
    res.write(
      `data: ${JSON.stringify({
        error: "发生错误",
      })}\n\n`
    );
    res.end();
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log("run");
});
